package com.mvc.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author H
 * @date 2023/1/10
 */
@RestController
@RequestMapping("rest")
public class TestRestTemplateController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/restTemplateForGet")
    public String restTemplateForGet() {
        String forObject = restTemplate.getForObject("http://127.0.0.1:8080/mediaType/testGet", String.class);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://127.0.0.1:8080/mediaType/testGet", String.class);
        System.out.println("状态码：" + responseEntity.getStatusCodeValue());
        System.out.println("body体：" + responseEntity.getBody());
        return forObject;
    }

    @GetMapping("/restTemplateForPost")
    public String restTemplateForPost() {
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        // 请求类型
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 绑定请求体和头
        HttpEntity<String> request = new HttpEntity<>("success", headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://127.0.0.1:8080/mediaType/testPost", request, String.class);
        System.out.println("状态码：" + responseEntity.getStatusCodeValue());
        System.out.println("body体：" + responseEntity.getBody());
        return "成功";
    }

    @GetMapping("/restTemplateForExchange")
    public String restTemplateForExchange() {
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        // 请求类型
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 绑定请求体和头
        HttpEntity<String> request = new HttpEntity<>("success", headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                "http://127.0.0.1:8080/mediaType/testPost",
                HttpMethod.POST,
                request,
                String.class);
        System.out.println("状态码：" + responseEntity.getStatusCodeValue());
        System.out.println("body体：" + responseEntity.getBody());
        return "成功";
    }

}
